﻿using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace System.Custom.Web
{
   public class CssReader
   {
      string FCss;
      char[] FAttrValueSplitter = new char[] { ':' };

      Dictionary<string, Dictionary<string, string>> FCssParams = new Dictionary<string, Dictionary<string, string>>();

      public CssReader(string css)
      {
         Css = css;
      }

      public string Css
      {
         get
         {
            return FCss;
         }
         set
         {
            foreach (Match g in Regex.Matches(value, @"(\#|\.)?(\w+\W*\w*){1,4}\{[^\}]{3,}\}"))
            {
               string selector = g.Value.SubstrBefore("{").Trim();

               Dictionary<string, string> attrs = null;

               if (!FCssParams.TryGetValue(selector, out attrs))
               {
                  attrs = new Dictionary<string, string>();
                  FCssParams[selector] = attrs;
               }
               foreach (string item in g.Value.SubstrAfter("{").Trim(' ', '\r', '\n', '\t', '}').Split(';'))
               {
                  string attr = item.Trim();
                  if (attr.Length == 0) continue;
                  string[] attrPair = attr.Split(FAttrValueSplitter, 2, StringSplitOptions.RemoveEmptyEntries);
                  attrs[attrPair[0]] = attrPair.Length == 2 ? attrPair[1] : "";
               }
            }

            //if (FCssParams.Count == 0) throw new InvalidDataException("Css is empty.");

            FCss = value;
         }
      }

      public string this[string group, string attr]
      {
         get
         {
            Dictionary<string, string> groupDic = null;

            if (FCssParams.TryGetValue(group, out groupDic))
            {
               string val = null;

               if (groupDic.TryGetValue(attr, out val)) return val.Trim();
            }
            return null;
         }
      }
   }
}